﻿/*
 * @Author Wujiajun
 * @Data 2021/2/20
 * @Description 实体管理器
 * 
 */

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EntityManager : MonoBehaviour
{
    private Dictionary<string, GameObject> m_Entities     = new Dictionary<string, GameObject>();
    private Dictionary<string, Transform>  m_EntityGroups = new Dictionary<string, Transform>();
    private Transform m_EnitityParent;

    private void Awake()
    {
        m_EnitityParent = this.transform.parent.Find("Entity");
    }


    private Transform GetEntityGroup(string group)
    {
        if (!m_EntityGroups[group])
            Debug.LogError("EntityGroup is not exists");
        return m_EntityGroups[group];
    }

    public void SetEntityGroup(List<string> groups)
    {
        for (int i = 0; i < groups.Count; i++)
        {
            GameObject group = new GameObject("EntityGroup-" + groups[i]);
            group.transform.SetParent(m_EnitityParent, false);
            m_EntityGroups[groups[i]] = group.transform;
        }
    }

    public void ShowEntity(string entityName, string entityGroup,string luaName)
    {
        //已被加载
        GameObject entity = null;
        if (m_Entities.TryGetValue(entityName, out entity))
        {
            EntityLogicBehaviour entityLogic = entity.GetComponent<EntityLogicBehaviour>();
            entityLogic.OnEntityShow();
            return;
        }

        //未被加载
        Manager.ResourceManager.LoadPrefab(entityName, (UnityEngine.Object obj) =>
        {
            GameObject entity2 = Instantiate(obj) as GameObject;
            m_Entities.Add(entityName, entity2);

            Transform parent = GetEntityGroup(entityGroup);
            entity2.transform.SetParent(parent, false);

            //为entity对象添加组件
            EntityLogicBehaviour entityLogic = entity2.AddComponent<EntityLogicBehaviour>();
            entityLogic.Init(luaName);
            entityLogic.OnEntityShow();
        });
    }
}
